package com.study.manage.mvc.v2;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qiniu.storage.BucketManager;
import com.qiniu.util.Auth;
import com.study.manage.dal.UserDetailRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.User;
import com.study.manage.domain.UserDetail;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.UploadController;
import com.study.manage.utils.ManageUtils;
import com.study.manage.utils.MapUtils;


@Controller
@RequestMapping("/v2/acc")
public class V2AccController extends UploadController {


    @RequestMapping(path = "son", method = RequestMethod.GET)
    public String article(HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        return "v2/acc/son";
    }

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserDetailRepository userDetailRepository;

    @ResponseBody
    @RequestMapping(path = "son-list", method = RequestMethod.GET)
    public AjaxResponse articleList(HttpServletRequest request, Long evaluateId,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = getUserInfo();
        Page<User> page = userRepository.findByParentIdOrIdAndState(su.getParentId(),
                su.getParentId(), LiveDieState.LIVE, pageable);
        return ajax.setObj(page.map(new Converter<User, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(User source) {
                Map<String, Object> map = MapUtils.convert(source);
                String url = "{qiniuUrl}/pic_avatar_{number}.jpg?a={time}";
                map.put("photo",
                        url.replace("{qiniuUrl}", qiniuUrl).replace("{number}", source.number + "")
                                .replace("{time}", new Date().getTime() + ""));

                UserDetail ud = userDetailRepository.findByUserId(source.id);
                map.put("realName", ud.realName);
                return map;
            }

        }));
    }

    @RequestMapping(path = "son-detail", method = RequestMethod.GET)
    public String son_detail(HttpServletRequest request, Long id, ModelMap model,
            HttpServletResponse response) {
        Map<String, Object> map = null;
        if (id == null) {
            map = MapUtils.convert(new User());
            map.put("photo", "");
            map.putAll(MapUtils.convert(new UserDetail()));
        } else {
            User user = userRepository.findOne(id);
            map = MapUtils.convert(user);
            String url = "{qiniuUrl}/pic_avatar_{number}.jpg?a={time}";
            map.put("photo",
                    url.replace("{qiniuUrl}", qiniuUrl).replace("{number}", user.number + "")
                            .replace("{time}", new Date().getTime() + ""));

            UserDetail ud = userDetailRepository.findByUserId(user.id);
            map.put("realName", ud.realName);
            map.put("autograph", ud.autograph);
            map.put("remarks", ud.remarks);

            map.put("addressProvince", ud.addressProvince);
            map.put("addressCity", ud.addressCity);
            map.put("addressDistrict", ud.addressDistrict);
            map.put("addressDetail", ud.addressDetail);

        }
        model.put("data", map);
        return "v2/acc/son-detail";
    }



    @Transactional
    @ResponseBody
    @RequestMapping(path = "son-detailSave", method = RequestMethod.POST)
    public AjaxResponse sonDetailSave(HttpServletRequest request, String name, Long id,
            String realName, String photo, HttpServletResponse response) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        List<User> users = userRepository.findByNotIdAndNameAndState(id, name, LiveDieState.LIVE,
                su.getType());
        if (!users.isEmpty()) {
            return ajax.setMsg("机构名称已经存在");
        }
        UserDetail rootUserDetail = userDetailRepository.findByUserId(su.getParentId());
        User user = null;
        if (id == null) {
            long number = 0;
            do {
                number = ManageUtils.getNumber(5);
                user = userRepository.findByNumber(number);
            } while (user != null);
            user = new User();
            user.type = su.getType();
            user.number = number;
            user.parentId = su.getParentId();
            user.inviteCode = ManageUtils.randomLetterStr(6);
            userRepository.save(user);

            UserDetail newUd = new UserDetail();
            newUd.realName = realName;
            newUd.userId = user.id;
            newUd.qudao = rootUserDetail.qudao;
            userDetailRepository.save(newUd);
        } else {
            user = userRepository.findOne(id);
        }

        MapUtils.copyObj(this.getRequestParameter(request), user, "id");
        userRepository.save(user);

        final Long userNumber = user.number;

        UserDetail ud = userDetailRepository.findByUserId(user.id);
        ud.nickName = user.name;
        MapUtils.copyObj(this.getRequestParameter(request), ud, "id");
        userDetailRepository.save(ud);

        try {
            BucketManager bucketManager = new BucketManager(Auth.create(ak, sk));
            bucketManager.fetch(photo, zone, "pic_avatar_" + userNumber + ".jpg");
        } catch (Exception e) {
            logger.error("upload image error", e);
        } finally {
        }

        return ajax;
    }



    @Transactional
    @ResponseBody
    @RequestMapping(path = "son-del", method = RequestMethod.POST)
    public AjaxResponse sonDel(HttpServletRequest request, Long id, LiveDieState state,
            HttpServletResponse response) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        User user = userRepository.findOne(id);
        if (user.parentId == null) {
            return ajax.setMsg("不能删除主账户");
        }
        MapUtils.copyObj(this.getRequestParameter(request), user, "id");
        userRepository.save(user);
        return ajax;
    }
}
